package safari.controller.member;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import safari.model.common.ListVO;
import safari.model.member.MemberService;
import safari.model.member.MemberVO;
import safari.model.message.IdAndPageVO;

public class MemberController extends MultiActionController {
	private MemberService ms;
	private String filePath;
	private File copyFile;
	public MemberController(MemberService ms) {
		this.ms = ms;
	}
	
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	/**
	 * 메인페이지로 가는 역할
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String home(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return "home";
	}

	public ModelAndView register(HttpServletRequest request,
			HttpServletResponse response, MemberVO mvo) throws SQLException {
		long now=System.currentTimeMillis();
		MultipartFile mFile=mvo.getUploadFile();
		mvo.setOrgFileName(mFile.getOriginalFilename());	
		mvo.setSaveFileName(now+mFile.getOriginalFilename());
		//업로드할 원본 파일을 이동시킬 파일 객체를 생성
		copyFile=new File(filePath+mvo.getSaveFileName());
		try {
			mFile.transferTo(copyFile);
			System.out.println("file upload.."+copyFile.getPath());
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				System.out.println("memberController의 register: mvo => "+mvo);
		String path2 = "error";
		// m==0 이면 id 중복 안된거
		//int m = ms.idCheck(mvo.getId());
		// n!=0 이면 회원가입 성공한거
		mvo.setId(request.getParameter("registerId"));
		int n = ms.register(mvo);
		// System.out.println("회원가입성공여부(n): "+n+"중복확인(m):"+m);
		if (n != 0)// 회원가입 성공하면(중복 안되고 제대로 insert 되면)
			path2 = "/member/register_ok";
		return new ModelAndView(path2);
	}

	// 중복이 안되면 result에 0이 넘어가서 회원가입 가능
	public ModelAndView idCheck(HttpServletRequest request,
			HttpServletResponse response) throws SQLException {
		String id = request.getParameter("id");
		// System.out.println("member controller: "+ms.idCheck(id));
		return new ModelAndView("JsonView", "result", ms.idCheck(id));
	}

	/**
	 * 회원 탈퇴하기 누르면 session 없애주고 회원탈퇴 실행한 후 메인페이지로 돌아가기 실행
	 */
	public String delete(HttpServletRequest request,
			HttpServletResponse response, HttpSession session)
			throws SQLException {
		String path = "/member/delete_ok";
		// login 안하고 주소에 치고 들어왔을 경우
		if (session.getAttribute("userInfo") == null) {
			path = "update";
		} else {
			MemberVO mvo = (MemberVO) session.getAttribute("userInfo");
			String id = mvo.getId();
			session.invalidate();
			ms.delete(id);
			System.out.println("aaa"+copyFile);
			if(copyFile!=null)
				copyFile.delete();
			//System.out.println("파일 잘 지워졌니?"+a);
		}
		return path;
	}

	/**
	 * 로그인 성공하면 1 반환, 실패하면 0 반환
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws SQLException
	 */
	public String login(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, MemberVO mvo)
			throws SQLException {
		mvo.setId(request.getParameter("loginId"));
		mvo.setPassword(request.getParameter("loginPassword"));
		MemberVO result = ms.login(mvo);
		String path = "error";
		if (result != null) {
			session.setAttribute("userInfo", result);
			path = "home";
		}
		if (result == null) {
			path = "/member/login_fail";
		}
		return path;
	}

	public String logout(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		session.invalidate();
		return "home";
	}

	public String goToRegister(HttpServletRequest request,
			HttpServletResponse response) {
		return "register";
	}

	/**
	 * 회원정보수정 누르면 정보수정하기 전에 비밀번호 한번 더 확인하는 페이지로 가는 메서드
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	public String goToUpdate(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		return "update_beforeChecking";
	}

	/**
	 * update 하려고 딱 들어갔을 때 보이는 update 되기 전 정보들이 적혀있는 페이지
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws SQLException
	 */
	public String updateBefore(HttpServletRequest request,
			HttpServletResponse response, HttpSession session)
			throws SQLException {
		String path = "/member/updateChecking_fail";
		// login 안하고 주소에 치고 들어왔을 경우
		if (session.getAttribute("userInfo") == null) {
			path = "update";
		} else {
			String paramPassword = request.getParameter("password");
			MemberVO mvo = (MemberVO) session.getAttribute("userInfo");
			String password = mvo.getPassword();
			// paramMvo: 세션에 있는 id인 사람의 모든정보
			MemberVO paramMvo = ms.getInfo(mvo.getId());
			// 정보 수정 하려고 쳐 넣은 비밀번호랑 세션 비밀번호랑 같으면
			if (paramPassword.equals(password)) {
				path = "update";
				request.setAttribute("info", paramMvo);
			}
		}
		return path;
	}

	public String update(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, MemberVO mvo)
			throws SQLException {
		System.out.println("test..."+mvo);
		// login 안하고 주소에 치고 들어왔을 경우
		String path = "error";
		if (session.getAttribute("userInfo") == null) {
			path = "update";
		} else {
			
			if(mvo.getUploadFile().getOriginalFilename()!=""){
			System.out.println("여기로 들어는 왔니");	
			long now=System.currentTimeMillis();
			MultipartFile mFile=mvo.getUploadFile();
			//업로드할 원본 파일을 이동시킬 파일 객체를 생성
			mvo.setOrgFileName(mFile.getOriginalFilename());	
			mvo.setSaveFileName(now+mFile.getOriginalFilename());
			copyFile=new File(filePath+mvo.getSaveFileName());
			try {
				mFile.transferTo(copyFile);
				System.out.println("update file upload.."+copyFile.getPath());
			} catch (IllegalStateException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			}//upload한 파일이 존재하면
			
			
			// mvo1 -> session 에 있는 user 정보
			// mvo -> 정보한 입력받은 정보(처음엔 grade, point 안들어 있음)
			MemberVO mvo1 = (MemberVO) session.getAttribute("userInfo");
			mvo.setId(mvo1.getId());
			//mvo.setOrgFileName(orgFileName)
			int result = ms.update(mvo);
			// 바뀐 정보를 가진 session으로 바꿔주려고 mvo에 grade, point 세팅한거
			mvo.setGrade(mvo1.getGrade());
			mvo.setPoint(mvo1.getPoint());
			// 성공하면
			if (result != 0) {
				path = "member/update_ok";
				session.setAttribute("userInfo", mvo);
				request.setAttribute("info", mvo);
			}
		}
		return path;
	}

	public String goToMypage(HttpServletRequest request,
			HttpServletResponse response) {
		return "myPage";
	}
	
	public String updateResult(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		return "member/update_result";
	}

	public ModelAndView deletePicture(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException{
		MemberVO mvo=(MemberVO) session.getAttribute("userInfo");
		mvo.setOrgFileName("");
		mvo.setSaveFileName("");
		session.setAttribute("userInfo", mvo);
		boolean ub=copyFile.delete();
		System.out.println("update시 사진 지워졌니"+ub);
		ms.updateDelPic(mvo);
		return new ModelAndView("JsonView","delPicResult",ub);
	}
	
	public ModelAndView viewMyTH(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException{
		MemberVO mvo=(MemberVO) session.getAttribute("userInfo");
		String id=mvo.getId();
		IdAndPageVO ipvo=new IdAndPageVO();
		System.out.println("나와봐!"+ipvo);
		ipvo.setId(id);
		if(request.getParameter("pageBuy")!=null){
			ipvo.setPage(Integer.parseInt(request.getParameter("pageBuy")));
		}
		//구입내역 뽑은 list
		ListVO buyList=ms.viewMyBuyTH(ipvo);
		
		IdAndPageVO ipvo2=new IdAndPageVO();
		ipvo2.setId(id);
		if(request.getParameter("pageSell")!=null){
		ipvo2.setPage(Integer.parseInt(request.getParameter("pageSell")));
		}
		System.out.println("나나나나나"+ipvo);
		//판매내역 뽑은 list
		ListVO sellList=ms.viewMySellTH(ipvo2);
		
		HashMap thMap=new HashMap();
		thMap.put("buyList", buyList);
		thMap.put("sellList", sellList);
		System.out.println("controller:buy:"+buyList+" ,sell:"+sellList);
		return new ModelAndView("member/viewMyTH","thResult",thMap);
	}
	
	public ModelAndView checkEmail(HttpServletRequest request, HttpServletResponse response) throws SQLException{
		String email=request.getParameter("email");
		int n=ms.checkEmail(email);
		return new ModelAndView("JsonView","result",n);
	}
	
}
